package com.jh.hts_jdk.io;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XlsxReader implements Iterable<List<Cell>>, Iterator<List<Cell>>{
	Workbook wb_in;
	Iterator<Row> active_iterator;
	public XlsxReader(File inputFile) throws InvalidFormatException, IOException{
		this(new XSSFWorkbook(inputFile));
	}

	public XlsxReader(Workbook wb) throws InvalidFormatException, IOException {
		wb_in = wb;
		wb_in.setActiveSheet(0);
		active_iterator = wb_in.getSheetAt(0).iterator();
	}

	
	public static List<Cell> row2List(Row r){
		int max_cell_num = r.getLastCellNum();
		List<Cell> row_list = new ArrayList<>(max_cell_num);
		for (int j = 0; j < max_cell_num; j++) {
			Cell cell = r.getCell(j);
			row_list.add(cell);
		}
		return row_list;
	}

	public List<List<Cell>> getConcent(String sheetName){
		return getConcent(getSheet(sheetName));
	}
	
	public List<List<Cell>> getConcent(Sheet sheet){
		List<List<Cell>> content_list = new LinkedList<>();
		for (Row r : sheet) {
			content_list.add(row2List(r));
		}
		content_list = new ArrayList<>(content_list);
		return content_list;
	} 
	
	public Sheet getSheet(String name) {
		return wb_in.getSheet(name);
	}
	
	public void setActiveSheet(int sheetIndex){
		wb_in.setActiveSheet(sheetIndex);
		active_iterator = wb_in.getSheetAt(sheetIndex).iterator();
	}
	
	public void setActiveSheet(String sheetName) {
		int index = wb_in.getSheetIndex(sheetName);
		wb_in.setActiveSheet(index);
	}
	
	public void setActiveSheet(Sheet sheet) {
		int index = wb_in.getSheetIndex(sheet);
		wb_in.setActiveSheet(index);
	}
	
	@Override
	public Iterator<List<Cell>> iterator() {
		return this;
	}
	
	@Override
	public boolean hasNext() {
		return active_iterator.hasNext();
	}
	
	@Override
	public List<Cell> next() {
		Row row_line = active_iterator.next();
		return row2List(row_line);
	}
	
	public void close() throws IOException{
		wb_in.close();
	}
}